package com.xuan.yuapigeteway;
import com.xuan.common.model.entity.InterfaceInfo;
import com.xuan.common.model.entity.User;
import com.xuan.common.service.InnerInterfaceInfoService;
import com.xuan.common.service.InnerUserInterfaceInfoService;
import com.xuan.common.service.InnerUserService;
import com.xuan.yuapiclientsdk.client.YuApiClient;
import com.xuan.yuapiclientsdk.utils.SignUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.http.server.reactive.SslInfo;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.http.server.RequestPath;
import java.net.InetSocketAddress;


import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");

    private static final String DESTINATION_HOST_IP = "http://localhost:8088";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 1. 请求日志
        HttpHeaders headers = request.getHeaders();
        String method = request.getMethod().toString();
        String id = request.getId();
        String path = request.getPath().value();
        Map<String, String> queryParams = request.getQueryParams().toSingleValueMap();
        Map<String, HttpCookie> cookies = request.getCookies().toSingleValueMap();
        String localAddress = request.getLocalAddress().getHostName();
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        log.info("请求唯一标识: " + id);
        log.info("请求路径: " + path);
        log.info("请求参数: " + queryParams);
        log.info("cookies: " + cookies);
        log.info("请求来源地址: " + localAddress);
        log.info("请求来源地址: " + remoteAddress);
        log.info("请求头: " + headers);
        log.info("请求方法: " + method);
        // 2. 访问控制(黑白名单)
        ServerHttpResponse response = exchange.getResponse();
        if (!IP_WHITE_LIST.contains(localAddress)) {
            return handleNoAuth(response);
        }
        // 3. 统一鉴权
        // 1) 获取用户信息,进而得到 accessKey 和 secretKey
        String accessKey = headers.getFirst("accessKey");
        User invokeUser = null;
        try {
            invokeUser = innerUserService.getInvokeUser(accessKey);
        } catch (Exception e) {
            log.error("getInvokeUser error", e);
        }
        if (invokeUser == null) {
            return handleNoAuth(response);
        }
        // 2) 根据请求头参数判断是否合法,并计算签名和比对签名
        String nonce = headers.getFirst("nonce");
        if (Integer.parseInt(nonce) > 10000) {
            return handleNoAuth(response);
        }
//        // 3) 当前时间大于 timestamp 超过 5分钟则视为无效(过期)
//        final long expireTime = 1000 * 60 * 5;
//        String timestamp = headers.getFirst("timestamp");
//        if (System.currentTimeMillis() - Long.parseLong(timestamp) > expireTime) {
//            return handleNoAuth(response);
//        }
        // 4) 使用相同参数(secretKey)和签名算法计算签名
        String clientSign = headers.getFirst("sign");
        String body = headers.getFirst("body");
        String secretKey = invokeUser.getSecretKey();
        String serverSign = SignUtils.getSign(body, secretKey);
        if (!serverSign.equals(clientSign)) {
            return handleNoAuth(response);
        }
        // 4. 根据请求地址和方法判断是否接口存在
        String url = DESTINATION_HOST_IP + path;
        InterfaceInfo interfaceInfo = null;
        try {
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(url, method);
        } catch (Exception e) {
            log.error("getInterfaceInfo error", e);
        }
        if (interfaceInfo == null) {
            return handleNoAuth(response);
        }
        // 5. 查询 user-interfaceInfo 表,查询用户剩余调用次数是否足够
        Long interfaceInfoId = interfaceInfo.getId();
        Long userId = invokeUser.getId();
        int restNum = innerUserInterfaceInfoService.getRestNum(interfaceInfoId, userId);
        if (restNum <= 0) {
            return handleNoInvokeNum(response);
        }
        // 6. 请求转发 + 统计调用次数 + 记录响应日志
        return handleResponse(exchange, chain, interfaceInfoId, userId);
    }

    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, long interfaceInfoId, long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            // 拼接字符串
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                        // 7. 调用成功，接口调用次数 + 1 invokeCount
                                        try {
                                            innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                                        } catch (Exception e) {
                                            log.error("invokeCount error", e);
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        String data = new String(content, StandardCharsets.UTF_8); //data
                                        sb2.append(data);
                                        // 打印日志
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    }));
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }


    private Mono<Void> handleNoAuth(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    private Mono<Void> handleNoInvokeNum(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.NOT_ACCEPTABLE);
        return response.setComplete();
    }

//    private Mono<Void> handleNoAuth(ServerHttpResponse response) {
//        response.setStatusCode(HttpStatus.FORBIDDEN);
//        return response.setComplete();
//    }

    @Override
    public int getOrder() {
        return -1;
    }

    @Bean
    public GlobalFilter customFilter() {
        return new CustomGlobalFilter();
    }

}